import store from "../store/index.js";

const initWebSocket = () => {
    let socket = new WebSocket('ws://your-backend/ws/orders');

    // 心跳检测（每30秒发送一次）
    const heartbeatInterval = setInterval(() => {
        if (socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify({ type: 'ping' }));
        }
    }, 30000);

    // 连接关闭时清理
    socket.onclose = () => {
        clearInterval(heartbeatInterval);
        console.log('WebSocket连接关闭，尝试重连...');
        setTimeout(initWebSocket, 5000); // 5秒后重连
    };

    // 错误处理
    socket.onerror = (error) => {
        console.error('WebSocket错误:', error);
        socket.close();
    };

    // 消息处理
    socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.type === 'order_update') {
            store.commit('UPDATE_ORDER_STATUS', {
                orderId: data.order.id,
                status: data.order.status
            });
        }
    };
};